/**
 * 京师书法资源文件加密
 */

const fs = require('fs');
const path = require('path');
const toolsNode = require('../libs/tools-node');
const password = 0xFB;

// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];
let _ext = path.extname(from).toLowerCase();
let _name = path.basename(from);
_name = _name.replace(/^de_/i, '');
let to = path.join(path.dirname(from), `en_${_name}`);
if (['.mp4', '.wav', '.mp3', '.wma', '.jpg', '.jpeg', '.png', '.gif', '.bmp'].includes(_ext)) {
  encodeFile(10);
} else if (['.txt', '.json', '.xml', '.html', '.css', '.js', '.log'].includes(_ext) || ['base.data', 'disk.disc'].includes(_name)) {
  encodeFile();
} else {
  encodeFile(10);
}

function encodeFile (len) {
  return new Promise((resolve, reject) => {
    fs.readFile(from, (err, data) => {
      if (err) {
        reject(`读取文件失败: ${_name}`);
      } else {
        let encrypted = Buffer.from(data);
        let length = len || encrypted.length;
        for (let i = 0; i < length; i++) {
          encrypted[i] = encrypted[i] ^ password;
        }
        toolsNode.writeFileSync(to, encrypted);
        resolve();
      }
    });
  });
};
